import { login, logout } from "@/api";
import { removeToken, setToken } from "@/utils/auth";
import { defineStore } from "pinia";
import { userKey } from "../index";
import {
  resetRouter,
  router,
  routerArrays,
  store,
  type userType
} from "../utils";
import { useMultiTagsStoreHook } from "./app/multiTags";

export const useUserStore = defineStore("pure-user", {
  state: (): userType => ({
    // 头像
    avatar: "",
    // 用户名
    username: "",
    // 昵称
    nickname: "",
    // 电话号码
    phone: "",
    // 页面级别权限
    roles: [],
    // 按钮级别权限
    permissions: []
  }),
  actions: {
    // 更新用户信息
    updateUserInfo(userInfo: Partial<userType>) {
      Object.keys(userInfo).forEach(key => {
        this[key] = userInfo[key];
      });
    },

    /** 登入 */
    async loginByUsername(data: { username: string; password: string }) {
      const res = await login(data);
      if (res.success) {
        const { data } = res;
        // 适配新的接口返回数据结构
        const tokenData = {
          token: data.token,
          expire: data.expire,
          userInfo: data.userInfo
        };
        this.avatar = data.userInfo.avatar;
        this.username = data.userInfo.username;
        this.nickname = data.userInfo.nickname;
        this.phone = data.userInfo.phone;
        setToken(tokenData);
      }
      return res;
    },

    logOut() {
      logout().finally(() => {
        this.avatar = "";
        this.username = "";
        this.nickname = "";
        this.phone = "";
        this.roles = [];
        this.permissions = [];
        removeToken();
        useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
        resetRouter();
        router.push("/login");
      });
    }
  },
  persist: {
    key: userKey,
    storage: localStorage
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
